package com.chen.demo.javase.algorithm.leetcode.editor.cn;
//给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。 
//
// 示例: 
//
// 输入: 3
//输出:
//[
// [ 1, 2, 3 ],
// [ 8, 9, 4 ],
// [ 7, 6, 5 ]
//] 
// Related Topics 数组 
// 👍 280 👎 0

import java.util.Arrays;

public class SpiralMatrixIi {
    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(solution(3)));

        System.out.println(Arrays.deepToString(solution(4)));

    }

    public static int[][] solution(int n) {
        int num = 1;
        int[][] result = new int[n][n];

        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;

        while (left <= right && top <= bottom) {
            // 从左到右
            for (int column = left; column <= right; column++) {
                result[top][column] = num;
                num++;
            }
            // 从上到下
            for (int row = top + 1; row <= bottom; row++) {
                result[row][right] = num;
                num++;
            }
            // 考虑只有一行情况
            if (top < bottom) {
                // 从右到左
                for (int column = right - 1; column >= left; column--) {
                    result[bottom][column] = num;
                    num++;
                }
            }
            if (left < right) {
                // 从下到上
                for (int row = bottom - 1; row > top; row--) {
                    result[row][left] = num;
                    num++;
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return result;
    }


    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[][] generateMatrix(int n) {
            return null;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}